337. House Robber III - LeetCode Solution


Tree DFS Dynamic programming

Python Code:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rob(self, root: Optional[TreeNode]) -> int:
        def trav(root):
            if not root:
                return [0, 0]
            left = trav(root.left)
            right = trav(root.right)
            withRoot = root.val + left[1] + right[1]
            withoutRoot = max(left) + max(right)
            return [withRoot, withoutRoot]
        return max(trav(root))
                


Comments

Submit
0 Comments
More Questions

99A - Help Far Away Kingdom
622B - The Time
1688C - Manipulating History
1169D - Good Triple
1675B - Make It Increasing
588A - Duff and Meat
1541B - Pleasant Pairs
1626B - Minor Reduction
1680A - Minimums and Maximums
1713A - Traveling Salesman Problem
1713B - Optimal Reduction
1710A - Color the Picture
1686B - Odd Subarrays
251A - Points on Line
427C - Checkposts
1159A - A pile of stones
508A - Pasha and Pixels
912A - Tricky Alchemy
1249A - Yet Another Dividing into Teams
1713C - Build Permutation
1699A - The Third Three Number Problem
1617B - GCD Problem
841A - Generous Kefa
1690B - Array Decrements
1692C - Where's the Bishop
104A - Blackjack
1438A - Specific Tastes of Andre
1711C - Color the Picture
1194C - From S To T
110B - Lucky String